<template>
  <qa-dialog v-model="modelValue.show" v-slot="slotProps" @onOpen="onOpen" :title="form.props.title">
    <qa-form v-model="form.data" @success="onFormSuccess" :closeDialog="slotProps.closeDialog"
      :action="form.props.action">
      <template #menuList>
        <el-tree ref="treeRef" style="max-width: 600px" :data="menuList" show-checkbox
          :default-expanded-keys="['system']" @check-change="treeChange"
          :default-checked-keys="modelValue.data.defaultMenu" node-key="menu_id" :props="{
            children: 'children',
            label: 'title',
          }" />
      </template>
    </qa-form>
  </qa-dialog>
</template>

<script lang="ts" setup>
import qaDialog from '@/components/qa-dialog.vue';
import qaForm from '@/components/qa-form.vue';
import Http from '@/util/request'
import type { ElTree } from 'element-plus'

const treeRef = ref<InstanceType<typeof ElTree> | null>(null);

const treeChange = (data: any) => {
  if (treeRef.value) {
    let checkedKeys = treeRef.value.getCheckedKeys();
    let halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
    let allCheckedKeys = checkedKeys.concat(halfCheckedKeys);
    form.value.data.menu = allCheckedKeys;
  }
}

const props = withDefaults(
  defineProps<{
    modelValue: any; // 定义为布尔值
    close: any
  }>(),
  {
  }
);
const form = ref<{
  data: {
    menu: any[]; // 明确 menu 是 TreeKey 数组
    defaultMenu: any[];
  };
  props: {
    title: string;
    action: string;
  };
  formType: string;
}>({
  data: {
    menu: [], // 初始化为空数组
    defaultMenu: [],
  },
  props: {
    title: "菜单绑定",
    action: "/admin/sysRole/bindMenu",
  },
  formType: 'add',
});

form.value.data = props.modelValue.data

watch(() => props.modelValue.show, (newVal) => {
  if (!newVal) {
    props.close();
  }
})

const onOpen = () => {
  form.value.data = props.modelValue.data
  getData()
}


const menuList = ref([])
const getData = async () => {
  const res = await Http.request({
    url: '/admin/sysMenu/getAll',
    method: 'post',
    data: {},
  })

  let current = JSON.parse(JSON.stringify(props.modelValue.data.menu))
  console.log('current', current)
  const list = res.data.data.list
  for (let i in list) {
    let item = list[i];
    let index = current.indexOf(item.parent_id);
    if (index > -1) {
      current.splice(index, 1);
    }
  }
  form.value.data.defaultMenu = current

  menuList.value = res.data.data.rows
}


const onFormSuccess = () => {
  props.close();
}
</script>
